<template>
  <div
       :style="{height:divHeight+ 'px'}"
       style="width: 100%;overflow:auto;display: flex; flex-direction: row">
    <div style="width: 95%;height: 100%">
      <div  id="container"></div>
    </div>
    <div v-if="drawTable">
      <div class="fieldMapbutton" style="margin-top: 5px">
        <el-button type="text" @click="nameMapping()">同名映射</el-button>
      </div>
      <div class="fieldMapbutton">
        <el-button type="text" @click="lineMapping">同行映射</el-button>
      </div>
      <div class="fieldMapbutton">
        <el-button type="text" @click="cancelMapping">取消映射</el-button>
      </div>
    </div>
  </div>

</template>
<script>
import { Graph } from "@antv/x6";
import { debounce, throttle } from "../../../util/index";
//禁止缩放
export default {
  // mixins: [autoResize],
  data() {
    return {
      graph: "",
      mappingValueList: [],
      drawTable: false,
      edgePositionY: "",
      scrollTop:0,
      graphHeight:''
    };
  },
  methods: {
    drawSourceTable(data) {
      this.drawTable = true;
      this.graph.removeCell(1);
      const node1 = {
        "id": 1,
        "shape": "er-rect",
        "attrs": {
          "label": {
            "text": "源头表字段"
          },
          "typeLabel": {
            "text": "类型"
          }
        },
        "width": 280,
        "height": 30,
        "position": {
          "x": 120,
          "y": 20
        },
        "ports": []
      };
      data.forEach((data, index) => {
        let a = {
          "id": "",
          "group": "list",
          "attrs": {
            "portNameLabel": {
              "text": "Gender"
            },
            "portTypeLabel": {
              "text": "BOOLEAN"
            }
          }
        };
        a.id = `1-${index}`;
        a.attrs.portNameLabel.text = data.name;
        a.attrs.portTypeLabel.text = data.type;
        node1.ports.push(a);
      });
      this.graph.addNode(node1);
      this.node1Height = 30*data.length+60
      if(!this.node2Height){
        this.graphHeight = this.node1Height
        this.graph.resize(1200, this.node1Height)
      }else if(this.node1Height>=this.node2Height){
        //加50是因为显示不全表格
        this.graph.resize(1200, this.node1Height)
        this.graphHeight = this.node1Height
      }else {
        this.graph.resize(1200, this.node2Height)
      }

    },
    drawToTable(data) {
      this.drawTable = true;
      this.graph.removeCell(2);
      const node2 = {
        "id": 2,
        "shape": "er-rect",
        "attrs": {
          "label": {
            "text": "目标表字段"
          },
          "typeLabel": {
            "text": "类型"
          }
        },
        "width": 280,
        "height": 30,
        "position": {
          "x": 800,
          "y": 20
        },
        "ports": []
      };
      data.forEach((data, index) => {
        let a = {
          "id": "",
          "group": "list",
          "attrs": {
            "portNameLabel": {
              "text": ""
            },
            "portTypeLabel": {
              "text": ""
            }
          }
        };
        a.id = `2-${index}`;
        a.attrs.portNameLabel.text = data.name;
        a.attrs.portTypeLabel.text = data.type;
        node2.ports.push(a);
      });
      this.graph.addNode(node2);
      this.node2Height = 30*data.length+60
      if(!this.node1Height){
        this.graphHeight = this.node2Height
        this.graph.resize(1200, this.node2Height)
      }else if(this.node2Height>=this.node1Height){
        //加50是因为显示不全表格
        this.graph.resize(1200, this.node2Height)
        this.graphHeight = this.node2Height
      }else {
        this.graph.resize(1200, this.node1Height)
      }

    },
    //同名映射
    nameMapping() {
      this.cancelMapping();
      this.graph.getCellById(1).getPorts().forEach((item1) => {
        this.graph.getCellById(2).getPorts().forEach((item2) => {
          if (item1.attrs.portNameLabel.text === item2.attrs.portNameLabel.text) {
            const customEdge = {
              "id": "",
              "shape": "edge",
              "source": {
                "cell": "1",
                "port": "1-1"
              },
              "target": {
                "cell": "2",
                "port": "2-1"
              },
              "attrs": {
                "line": {
                  "stroke": "#A2B1C3",
                  "strokeWidth": 2
                }
              },
              "zIndex": 0
            };
            customEdge.id = item1.id;
            customEdge.source.cell = 1;
            customEdge.source.port = item1.id;
            customEdge.target.cell = 2;
            customEdge.target.port = item2.id;
            this.graph.addEdge(customEdge);
          }
        });
      });
    },
    //同行映射
    lineMapping() {
      this.cancelMapping();
      this.graph.getCellById(1).getPorts().forEach((item1) => {
        this.graph.getCellById(2).getPorts().forEach((item2) => {
          if (item1.id.slice(2) === item2.id.slice(2)) {
            const customEdge = {
              "id": "",
              "shape": "edge",
              "source": {
                "cell": "",
                "port": ""
              },
              "target": {
                "cell": "",
                "port": ""
              },
              "attrs": {
                "line": {
                  "stroke": "#A2B1C3",
                  "strokeWidth": 2
                }
              },
              "zIndex": 0
            };
            customEdge.id = item1.id;
            customEdge.source.cell = 1;
            customEdge.source.port = item1.id;
            customEdge.target.cell = 2;
            customEdge.target.port = item2.id;
            this.graph.addEdge(customEdge);
          }
        });
      });
    },
    //取消映射
    cancelMapping() {
      const edges = this.graph.getEdges();
      this.graph.removeCells(edges);
    },
    //重置表单
    restGraph() {
      const nodes = this.graph.getNodes();
      this.graph.removeCells(nodes);
      this.drawTable = false
    },
    //获取连线的值
    mappingValue() {
      let mappingValueList = [];
      this.graph.getEdges().forEach((item) => {
        //获取线的起始,结束端口
        const sourcePort = item.getSource();
        const targetPort = item.getTarget();
        let a = {
          srcColumnName: "",
          srcColumnType: "",
          targetColumnName: "",
          targetColumnType: ""
        };
        // 根据端口的cell获取具体的起始节点信息
        this.graph.getCellById(sourcePort.cell).getPorts().forEach((port) => {
          if (sourcePort.port === port.id) {
            a.srcColumnName = port.attrs.portNameLabel.text;
            a.srcColumnType = port.attrs.portTypeLabel.text;
          }
        });
        // 根据端口的cell获取具体的终点节点信息
        this.graph.getCellById(targetPort.cell).getPorts().forEach((port) => {
          if (targetPort.port === port.id) {
            a.targetColumnName = port.attrs.portNameLabel.text;
            a.targetColumnType = port.attrs.portTypeLabel.text;
          }
        });
        mappingValueList.push(a);
        this.mappingValueList = mappingValueList;
      });
      return this.mappingValueList;
    },
    //反显连线
    invertEdges(data) {
      this.graph.getCellById("1").getPorts().forEach((item1) => {
        this.graph.getCellById("2").getPorts().forEach((item2) => {
          data.forEach((item3) => {
            if (item3.srcColumnName === item1.attrs.portNameLabel.text && item3.targetColumnName === item2.attrs.portNameLabel.text) {
              const customEdge = {
                "id": "",
                "shape": "edge",
                "source": {
                  "cell": "1",
                  "port": "1-1"
                },
                "target": {
                  "cell": "2",
                  "port": "2-1"
                },
                "attrs": {
                  "line": {
                    "stroke": "#A2B1C3",
                    "strokeWidth": 2
                  }
                },
                "zIndex": 0
              };
              customEdge.id = item1.id;
              customEdge.source.cell = 1;
              customEdge.source.port = item1.id;
              customEdge.target.cell = 2;
              customEdge.target.port = item2.id;
              this.graph.addEdge(customEdge);
            }
          });

        });
      });
    },

  },
  computed: {
    divHeight() {
      return this.graphHeight;
    },
  },
  created() {
    this.$bus.$on("getMappingValue", (data) => {
      this.mappingValue();
    });
  },
  mounted() {
    this.node2Height = ''
    this.node1Height = ''
    const graph = this.graph = new Graph({
      container: document.getElementById("container"),
      autoResize: true,
      // width: document.getElementById('container').clientWidth,
      // width: 810,
      // height: 100,
      interacting: {
        nodeMovable: false,
        edgeMovable: true
      },
      connecting: {
        allowBlank: false,
        allowLoop: false,
        allowNode: false,
        router: {
          name: "er",
          args: {
            offset: 8,
            direction: "L"
          }
        },
        createEdge() {
          return this.createEdge({
            attrs: {
              line: {
                stroke: "#efefef",
                strokeWidth: 1
                // targetMarker:null
              }
            }
          });

        }
      }
    });
    const LINE_HEIGHT = 30;
    const NODE_WIDTH = 280;
    Graph.registerPortLayout(
      "erPortPosition",
      (portsPositionArgs) => {
        return portsPositionArgs.map((_, index) => {
          return {
            position: {
              x: 0,
              y: (index + 1) * LINE_HEIGHT
            },
            angle: 0
          };
        });
      },
      true
    );
    Graph.registerNode(
      "er-rect",
      {
        inherit: "rect",
        markup: [
          {
            tagName: "rect",
            selector: "body"
          },
          {
            tagName: "text",
            selector: "label"
          },
          {
            tagName: "text",
            selector: "typeLabel"
          }
        ],
        attrs: {
          body: {
            strokeWidth: 1,
            stroke: "#454857",
            fill: "#454857"
          },
          label: {
            fontWeight: "bold",
            fill: "#ffffff",
            fontSize: 12,
            refX: 40,
            refY: 15
          },
          typeLabel: {
            fontWeight: "bold",
            fill: "#ffffff",
            fontSize: 12,
            refX: 195,
            refY: 15
          }

        },
        ports: {
          groups: {
            list: {
              markup: [
                {
                  tagName: "rect",
                  selector: "portBody"
                },
                {
                  tagName: "text",
                  selector: "portNameLabel"
                },
                {
                  tagName: "text",
                  selector: "portTypeLabel"
                }
              ],
              attrs: {
                portBody: {
                  width: NODE_WIDTH,
                  height: LINE_HEIGHT,
                  strokeWidth: 1,
                  stroke: "#363638",
                  fill: "#454857",
                  magnet: true
                },
                portNameLabel: {
                  fill: "#ffffff",
                  ref: "portBody",
                  refX: 30,
                  refY: 10,
                  fontSize: 11
                },
                portTypeLabel: {
                  fill: "#ffffff",
                  ref: "portBody",
                  refX: 180,
                  refY: 10,
                  fontSize: 11
                }
              },
              position: "erPortPosition"
            }
          }
        }
      },
      true
    );
    this.graph.on("edge:mouseenter", ({ edge }) => {
      edge.addTools([{
        name: "button-remove",
        args: {
          distance: -50
        }
      }]);
    });
    this.graph.on("edge:mouseleave", ({ edge }) => {
      edge.removeTools();
    });
    this.graph.on("edge:mousedown", ({ e, x, y, cell, view }) => {
      this.edgePositionY = y;
    });
    const cb = throttle(({ e, x, y, cell, view }) => {
      this.$emit('scrollEvent',{y,cell})
    }, 50);
    this.graph.on("edge:mousemove", cb);
    this.graph.on("edge:mouseup", () => {
      this.$emit('clearTimer')
      // this.isGoing = false;
      // clearInterval(this.goingTask);
    });
  }

};
</script>
<style>

</style>
